
package formServlets;
import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Persistent;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreAttributes;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

import javax.servlet.http.HttpServlet;

//import guestbook.PMF;

public class  UserAcademicInfoServlet  extends HttpServlet  {

	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		getServletContext().getRequestDispatcher("SNSP.html").forward(req, resp);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("In UserAcademicInfoServlet");
		Cookie cookies [] = request.getCookies ();
		Cookie myCookie = null;
		Cookie schoolCookie=null;
		if (cookies != null)
		{
			System.out.println("cookies exist");
			for (int i = 0; i < cookies.length; i++)
			{
				System.out.println("cookie " + i + " is " + cookies[i].getName() + " value = "+ cookies[i].getValue());
				if (cookies [i].getName().equals ("passUsername"))
				{
					System.out.println("reading  username cookie");
					myCookie = cookies[i];
				}
			
				if (cookies [i].getName().equals ("schoolId"))
				{
					System.out.println("reading schoolId cookie");
					schoolCookie = cookies[i];
				}
			}
		}
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		String degreeType= request.getParameter("degreeType");
		String major = request.getParameter("Major");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		//String entranceExamType = request.getParameter("entranceExamType");
		String examScore = request.getParameter("examScore");
		String funded = request.getParameter("funded");
		String GPA= request.getParameter("GPA");
		String employed= request.getParameter("employed");
		String Userid=myCookie.getValue();
		String schoolid = schoolCookie.getValue();		
		Entity user = new Entity("UserAcademicInfo",Userid);
		user.setProperty("Userid", Userid);
		user.setProperty("degreeType",degreeType);
		user.setProperty("schoolId", schoolid);
		user.setProperty("Major", major);
		user.setProperty("startDate", startDate);
		user.setProperty("endDate", endDate);
	//	user.setProperty("entranceExamType", entranceExamType);
		user.setProperty("examScore", examScore);
		user.setProperty("funded", funded);
		user.setProperty("GPA", GPA);
		user.setProperty("employed", employed);
        datastore.put(user);
		
		try {
			Key key = KeyFactory.createKey("UserAcademicInfo", Userid);
			Entity e=datastore.get(key);
			System.out.print(e.getProperties());
			
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DatastoreAttributes ds=datastore.getDatastoreAttributes();
		DatastoreAttributes.DatastoreType dst= ds.getDatastoreType();
		System.out.print(dst.name());
		
		Query q1 = new Query("SchoolInfo");
		q1.addFilter("SchoolId", Query.FilterOperator.EQUAL,schoolid  );
		PreparedQuery pq1 = datastore.prepare(q1);
		for (Entity result : pq1.asIterable())
		{
			int totalStudents=(Integer) result.getProperty("totalStudents");
			Long GREscore=(Long) result.getProperty("avgGREScore");
			Long employmentPercentage=(Long) result.getProperty("employmentPercentage") ;
		   // String AvgGPA= (String)result.getProperty("avgStudentGPA");
			//float avgStudentGPA= Float.parseFloat(AvgGPA) ;
			Long avgStudentGPA = (Long)result.getProperty("avgStudentGPA");
		   // String fundedStudents=(String)result.getProperty("percentOfFundedStudents");
			//float percerntOfFundedStudents= Float.parseFloat(fundedStudents) ;
			Long percentOfFundedStudents= (Long)result.getProperty("percentOfFundedStudents");
			
			
			// totalStudents value is incremented when the student adds the school to his education but
			// other details of student were not added 
			// to calculate we have to deduct 1 from totalstudent so as to get prev number of students
			
			// calculate avg  GRE score for schoolinfo
			Long totalGRE= ((GREscore*(totalStudents-1))+ Integer.parseInt(examScore))/totalStudents;
			result.setProperty("avgGREScore", totalGRE);
		
			// calculate employment rate for schoolinfo
			Long totalemployedStudent= ((totalStudents-1)*employmentPercentage)/100;
			float calEmployment=0;
			if(employed.equalsIgnoreCase("yes"))
			{
				calEmployment=(totalemployedStudent+1/totalStudents)*100;
			}
			else
			{
				calEmployment=(totalemployedStudent/totalStudents)*100;
			}
			result.setProperty("employmentPercentage", calEmployment);
			
			// calculate avg GPA 
			float totalGPA= avgStudentGPA*(totalStudents-1);
			float avggpa= (totalGPA+ Float.parseFloat(GPA))/totalStudents;
			result.setProperty("avgStudentGPA", avggpa);
			
			// calculate percent of funded student
			Long totalfunded= ((totalStudents-1)*percentOfFundedStudents)/100;
			//float 
			if(funded.equalsIgnoreCase("selfFunded"))
			{
				percentOfFundedStudents=(totalfunded/totalStudents)*100;
			}
			else
			{
				percentOfFundedStudents= ((totalfunded+1)/totalStudents)*100;
			}
			result.setProperty("percerntOfFundedStudents", percentOfFundedStudents);
			
		}
		//response.sendRedirect("successfulSignup.html");
 
	}
 
}
